package com.newblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newblog.common.ResultAjax;
import com.newblog.common.SessionUtils;
import com.newblog.mapper.ArticleMapper;
import com.newblog.mapper.UserMapper;
import com.newblog.model.ArticleInfo;
import com.newblog.model.userinfo;
import com.newblog.model.vo.UserInfoVo;
import com.newblog.service.ArticleService;
import com.newblog.service.UserService;
import com.sun.org.apache.xpath.internal.functions.FuncTrue;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with Intellij IDEA.
 * Description;
 * UserInfo:TQ02
 * Data:2023-12-10
 * Time:14:43
 * Text：
 */
@RestController
@RequestMapping("/art")
public class ArticleController {

    private static final int _DESC_LENGTH = 120; // 文章简介的长度

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserService userService;

//查询自身博客列表
    @RequestMapping("/mylist")
    public ResultAjax myList(HttpServletRequest req){
        userinfo user= SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"请先登陆");
        }
        List<ArticleInfo> t1=articleMapper.selectList(new QueryWrapper<ArticleInfo>().eq("userId",user.getUserid()));
        if(t1!=null&& t1.size()>0){
            t1.stream().parallel().forEach((art) ->{
                if(art.getContent().length()>120){
                    art.setContent(art.getContent().substring(0,120));
                }
            });
        }
        return ResultAjax.succ(t1);
    }
//    查询所有文章
    @RequestMapping("/list")
    public ResultAjax list(){
        List<ArticleInfo> t1=articleService.list();
        return ResultAjax.succ(t1);
    }

//删除自身博客
    @RequestMapping("/delete")
    public ResultAjax deltet(Integer aid,HttpServletRequest req){
        if(aid==null || aid<=0){
            return ResultAjax.fail(-1,"参数错误");
        }
        userinfo user= SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"请先登陆");
        }
        System.out.println(user.getUserid());
        int num=articleService.delete(aid,user.getUserid());

        return ResultAjax.succ(num);
    }
//新增个人博客
    @RequestMapping("/add")
    public ResultAjax add(ArticleInfo art,HttpServletRequest req){
        userinfo user= SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"请先登陆");
        }

        if(art==null || !StringUtils.hasLength(art.getTitle()) ||
                !StringUtils.hasLength(art.getContent())){
            return ResultAjax.fail(-1,"非法参数");
        }
        art.setUserId(user.getUserid());
        art.setName(user.getUsername());

        if(articleService.save(art))
            return ResultAjax.succ(1);
        return ResultAjax.fail(-1,"后端出问题");
    }
//重新编辑博客
    @RequestMapping("/edit")
    public ResultAjax edit(int id,HttpServletRequest req){
        if(id<0){
            return ResultAjax.fail(-1,"参数错误");
        }
        userinfo user= SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"请先登陆");
        }
        ArticleInfo art=articleMapper.selectOne(new QueryWrapper<ArticleInfo>().eq("articleId",id));
        if(art==null ){
            return ResultAjax.fail(-1,"参数错误");
        }
        return ResultAjax.succ(art);

    }
    //修改个人博客
    @RequestMapping("/update")
    public ResultAjax update(ArticleInfo art,HttpServletRequest req){
        userinfo user= SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"请先登陆");
        }
        System.out.println(art);
        if(art==null || !StringUtils.hasLength(art.getTitle()) ||
                !StringUtils.hasLength(art.getContent())){
            return ResultAjax.fail(-1,"非法参数");
        }
        art.setUserId(user.getUserid());
        art.setName(user.getUsername());
        int num=articleService.update(art);
            return ResultAjax.succ(num);
    }
    @RequestMapping("/detail")
    public ResultAjax detail(Integer id,HttpServletRequest req) throws ExecutionException, InterruptedException {
        // 1.参数效验
        if (id == null || id <= 0) {
            return ResultAjax.fail(-1, "非法参数！");
        }
        // 2.查询文章详情,通过查询第几篇文章查询文章的信息
        ArticleInfo articleinfo = articleMapper.selectOne(new QueryWrapper<ArticleInfo>().eq("articleId",id));
        if (articleinfo == null || articleinfo.getArticleId() <= 0) {
            return ResultAjax.fail(-1, "非法参数！");
        }
        // 3.根据 id 查询用户的详情
        FutureTask<UserInfoVo> userTask=new FutureTask(()->{
// todo:调用service;                通关查询文章的作者讯号查询到作者信息
            return userService.getUserById(articleinfo.getUserId());
        });
        taskExecutor.submit(userTask);
        FutureTask<Integer> artCountTask =new FutureTask<>(()->{
                            //通过作者序号查询文章信息，并且会统计文章数目
            return articleService.getDetail(articleinfo.getUserId());
        });

         taskExecutor.submit(artCountTask);
        // 等待任务执行完成
        UserInfoVo u1=userTask.get();
        int artCount=artCountTask.get();
        u1.setArtcount(artCount);

        HashMap<String,Object> t1=new HashMap<>();
        t1.put("use", u1);
        t1.put("art", articleinfo);
        return ResultAjax.succ(t1);

    }
//阅读量自增
    @PostMapping("/increment")
    public ResultAjax increment(Integer id){

        int num1=articleService.getinsert(id);
        if(num1==1){
            return ResultAjax.succ("阅读成功");
        }
        return ResultAjax.fail(-1,"失败");
    }
//查询分页功能
    @RequestMapping("/getlistbypage")
    public  ResultAjax getlistbypage(Integer pindex,Integer psize) throws ExecutionException, InterruptedException {
        //加工参数
        if(pindex == null || pindex<1){
            pindex =1;
        }
        if(psize == null ||psize<1){
            psize=2;
        }
        Integer finalpindex=pindex;
        //并发任务执行文章列表和总页数的查询
        Integer finalPsize = psize;
        FutureTask<List<ArticleInfo>> ListTask=new FutureTask<>(()->{
            int finalofest=finalPsize*(finalpindex-1);  //当前页面个数和第几页开始
            return  articleService.getListByPage(finalPsize,finalofest);

        });
        FutureTask<Integer> sizeTask=new FutureTask<>(()->{
            int total =articleService.getCount();
            double sizeTemp=(total * 1.0)/(finalPsize * 1.0);
            return (int)Math.ceil(sizeTemp);
        });
        taskExecutor.submit(ListTask);
        taskExecutor.submit(sizeTask);
        List<ArticleInfo> t1=ListTask.get();
        int size=sizeTask.get();
        HashMap<String,Object> map=new HashMap<>();
        map.put("list",t1);
        map.put("size",size);

        return ResultAjax.succ(map);

     }

}
